<?php
defined ( 'BASEPATH' ) or exit ( 'No direct script access allowed' );
class Cost_model extends CI_Model {
	public function __construct() {
		parent::__construct ();
	}
	/*
	 * 根据分页和支出名称返回支出列表
	 */
	public function find_all_costs($name,$per_page,$offset){
		if(!empty($name)){
			$this->db->like('name', $name);
		}
		$this->db->limit($per_page, $offset);
		$this->db->order_by("id", "desc");
		$query = $this->db->get('t_cost');
		return $query->result_array();
	}
	/*
	 * 根据支出名称返回支出数量
	 */
	public function count_costs($name){
		if(!empty($name)){
			$this->db->like('name', $name);
		}
		$query = $this->db->get('t_cost');
		return $query->num_rows();
	}
	/*
	 * 根据ID返回支出
	 */
	public function load($id){
		$query = $this->db->get_where('t_cost',array('id' => $id));
		if ($row = $query->row_array()){
			return $row;
		}
		return array();
	}
	/*
	 * 添加支出信息
	 */
	public function create($cost){
		$this->db->insert('t_cost', $cost);
		return $this->db->insert_id();
	}
	/*
	 * 删除支出信息
	 */
	public function delete($id){
		$this->db->where('id', $id);
		$this->db->delete('t_cost');
		return $this->db->affected_rows()>0;
	}
	/*
	 * 根据日期返回支出信息
	 */
	public function find_export_costs($cost_time){
		$this->db->where('cost_time', $cost_time);
		$query = $this->db->get('t_cost');
		return $query->result_array();
	}
	/*
	 * 根据起始日期得到采购支出
	 */
	public function count_costs_by_date($startdate,$enddate){//
		$sql="select sum(total) as total from t_cost 
					where productid is not null and t_cost.cost_time>='".$startdate."' and  t_cost.cost_time<='".$enddate."'";
		$query = $this->db->query($sql);
		return $query->result_array();
	}
	/*
	 * 根据起始日期得到其他支出
	 */
	public function count_othercosts_by_date($startdate,$enddate){//
			$sql="select sum(total) as total from t_cost 
					where productid is  null and t_cost.cost_time>='".$startdate."' and  t_cost.cost_time<='".$enddate."'";
		$query = $this->db->query($sql);
		return $query->result_array();
	}
	/*
	 * 根据起始日期得到采购的商品信息
	 */
	public function get_products_by_date($startdate,$enddate){//
			$sql="select productid,name,price,unit,sum(amount) as amount from t_cost 
					where productid is not null and t_cost.cost_time>='".$startdate."' and  t_cost.cost_time<='".$enddate."' group by productid";
		$query = $this->db->query($sql);
		return $query->result_array();
	}
	/*
	 * 根据起始日期和商品ID得到采购的商品信息(用于添加库存商品)
	 */
	public function get_cost_by_date_product($productid,$startdate,$enddate){//
			$sql="select productid,name,price,unit,sum(amount) as amount from t_cost 
					where productid=".$productid." and t_cost.cost_time>='".$startdate."' and  t_cost.cost_time<='".$enddate."'";
		$query = $this->db->query($sql);
		return $query->row_array();
	}
}